package com.yunxiao.cloud.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @description: 深拷贝
 * @date: 2019/12/30 17:37
 * @author: yunxiao
 * @version: 1.0
 */
public class CloneUtil<T> {
    private static Logger logger = LoggerFactory.getLogger(CloneUtil.class);

    /**
     * 反射clone
     *
     * @param t
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public T clone(T t) throws IllegalAccessException, InstantiationException {
        Class clazz = t.getClass();
        return (T) clazz.newInstance();
    }

    /**
     * 序列化
     *
     * @param object
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T extends Serializable> T clone(T object) {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bout);
            oos.writeObject(object);

            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bin);
            // 此处不需要释放资源，说明：调用ByteArrayInputStream或ByteArrayOutputStream对象的close方法没有任何意义
            // 这两个基于内存的流只要垃圾回收器清理对象就能够释放资源，这一点不同于对外部资源（如文件流）的释放
            return (T) ois.readObject();
        } catch (Exception e) {
            logger.error("clone error: ", e);
        }
        return null;
    }
}
